import React, { Component } from 'react';
import { ScrollView, View, Platform } from 'react-native';
import { observer } from 'mobx-react';
import _ from 'lodash';
import { Actions } from 'react-native-router-flux';
import Icon from 'react-native-vector-icons/FontAwesome';
import Modal from '../../../components/Modal';
import Former, {
  validate,
  setFieldsValue,
  formStore
} from '../../../components/Former';
import Button from '../../../components/Button';
import ResultList from '../common/resultList';
import styles from './styles';

import { idCardRule, mobileRule } from '../../../utils/rules';

@observer
class Form extends Component {
  state = {
    value: {},
    searchResult: [],
    keyword: ''
  };
  _validate = () => {
    validate((err, val) => {
      if (!err && _.isFunction(this.props.onSubmit)) {
        val.eventId = this.props.eventId
        this.props.onSubmit(val);
      }
    });
  };

  onSearch = keyword => {
    const kw = _.trim(keyword);
    if (kw) {
      this.props.customers.search(kw).then(
        list => {
          if (Platform.OS === 'ios') {
            const values = formStore.getValues();
            Actions.replace('searchResults', {
              props: this.props,
              backTo: Actions.currentScene,
              list,
              keyword,
              values
            });
          } else if (Platform.OS === 'android') {
            this.setState({
              searchResult: list,
              keyword
            });
          }
        }
      );
    }
  };
  closeModal = () => {
    this.setState({
      searchResult: [],
      keyword: ''
    });
  };
  setValue = value => {
    const {
      name: customerName,
      mobile: customerMobile,
      idCardNo: customerIdNo,
    } = value;
    setFieldsValue.call(formStore, {
      customerName,
      customerMobile,
      customerIdNo,
    });
    this.setState({
      keyword: '',
      searchResult: []
    });
  };
  render() {
    const { values: {
      customerName, customerMobile, customerIdNo, subscriptionNo,subscriptionAmount
    } = {} } = this.props;
    const fields = [
      {
        title: '必要信息',
        type: 'Title'
      },
      {
        label: '认购号',
        placeholder: '请输入认购号',
        type: 'TextInput',
        key: 'subscriptionNo',
        initialValue: subscriptionNo,
        rules: [{ require: true }],
        keyboardType: 'numeric',
      },
      {
        label: '认购金额(元)',
        type: 'Number',
        key: 'subscriptionAmount',
        initialValue: subscriptionAmount,
        rules: [{ require: true }],
        allowEdit: true,
        maximumValue: 999999,
        minimumValue: 0,
      },
      {
        label: '客户姓名',
        placeholder: '请选择客户姓名',
        type: 'TextInput',
        key: 'customerName',
        initialValue: customerName,
        rules: [{ require: true }],
        extra: ({ value }) => (
          <Button
            onPress={this.onSearch.bind(null, value)}
            icon={<Icon name="search" color="#fff" />}
            type="primary"
            style={{ height: 44, width: 44, borderRadius: 0 }}
          />
        )
      },
      {
        title: '选填信息',
        type: 'Title'
      },
      {
        label: '客户手机号',
        placeholder: '请输入客户手机号',
        type: 'TextInput',
        key: 'customerMobile',
        initialValue: customerMobile,
        rules: [
          {
            validation: (value, cb) => {
              if (value && !mobileRule(value)) {
                cb('手机号格式不正确');
              } else {
                cb();
              }
            }
          }
        ]
      },
      {
        label: '客户身份证',
        placeholder: '请输入客户身份证号',
        type: 'TextInput',
        key: 'customerIdNo',
        initialValue: customerIdNo,
        rules: [
          {
            validation: (value, cb) => {
              if (value && !idCardRule(value)) {
                cb('身份证号格式不正确');
              } else {
                cb();
              }
            }
          }
        ]
      },
    ];
    return (
      <View style={{ flex: 1 }}>
        {Platform.OS === 'android' ? <Modal
          visible={!_.isEmpty(this.state.searchResult)}
          title={`关键字“${this.state.keyword}”，${
            this.state.searchResult.length
            }个结果`}
          footer={<Button title="关闭" onPress={this.closeModal} />}
        >
          <ScrollView style={styles.resultList}>
            {_.map(this.state.searchResult, data => (
              <ResultList
                key={data.customerId}
                data={data}
                onPress={this.setValue.bind(null, data)}
              />
            ))}
          </ScrollView>
        </Modal> : null}

        <Former
          fields={fields}
          bottom={
            <Button
              onPress={this._validate}
              type="primary"
              title="提交家庭保单信息"
            />
          }
        />
      </View>
    );
  }
}

export default Form;
